package ltd.sshine.bot.config.scan;

//import ltd.sshine.bot.config.annotation.EventMapping;
//import ltd.sshine.eventscan.config.annotation.EventHandler;
//import ltd.sshine.eventscan.config.annotation.EventMapping;

import ltd.sshine.bot.config.annotation.EventHandler;
import ltd.sshine.bot.config.annotation.EventMapping;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class EventHandlerMappingFactory {
//    private static Logger logger = Logger.getLogger(ServletHandlerMappingFactory.class);

    private static final Map<String, Method> servletHandlerMapping = new HashMap<>();


    public static void addClassMapping(Class<?> clazz) {
        String event=null;
        EventHandler handlerMapping = clazz.getAnnotation(EventHandler.class);
        if (handlerMapping != null) {
            event = handlerMapping.value();
        }
        if (event != null) {
            EventHandlerFactory.put(clazz);
//            System.out.println("载入处理类:" + clazz.getName() + " event:" + event);
            scanHandlerMethod(clazz,event);
        }
    }

    public static void scanHandlerMethod(Class<?> clazz,String classMapping) {
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            EventMapping handlerMapping = method.getAnnotation(EventMapping.class);
            if (handlerMapping != null) {
                String mapping = handlerMapping.value();
                mapping = "".equals(classMapping)?mapping:classMapping+" " + mapping;
                addMethodMapping(mapping,method);
            }
        }
    }

    public static void addMethodMapping(String event,Method method) {
//        System.out.println(" 载入方法:" + method.getName() + " 事件:" +event);
        Method handlerMethod = servletHandlerMapping.get(event);
        if(handlerMethod != null){
            throw new IllegalArgumentException(" event :" + event + " 事件已经载入 :" + handlerMethod);
        }else{
            servletHandlerMapping.put(event, method);
        }
    }

    public static Method getMethodMapping(String event) {
        return servletHandlerMapping.get(event);
    }
}
